<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<html>
<head>
    <title>购买商品</title>
    <link rel="stylesheet" href="css/buy.css">
</head>
<body>
<%@include file="header.jsp" %>
<section>
    <div id="address">
        <a id="add_address" onclick="add_address()">添加地址</a>
        <ul class="address_is_default">
        </ul>
    </div>
    <div id="address_table">
        <div id="header_problem">
            <span id="problem_head">选择地址</span>
            <span class="close" onclick="address_all_toggle()">&times;</span>
        </div>
        <ul class="address_all_li">
        </ul>
    </div>
    <div id="address_add">
        <div id="header">
            <span id="head">添加地址</span>
            <span class="close" onclick="add_address()">&times;</span>
        </div>
        <ul class="address_add_li">
            <li>
            <label for="name">昵&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;称：</label>
            <input type="text" id="name">
            </li>
            <li>
            <label for="phone">联系电话：</label>
            <input type="text" id="phone">
            </li>
            <li>
            <label for="address_name">详细地址：</label>
            <input type="text" id="address_name">
            </li>
            <li>
            <label for="default">是否是默认地址：</label>
            <input type="checkbox" id="default">
            </li>
        </ul>
        <div class="modify-footer">
            <a class="btn-confirm" onclick="addAddress()">添加</a>
            <a href="#" class="btn-cancel" onclick="add_address()">取消</a>
        </div>
    </div>
    <div id="store_commodity">
    </div>
    <div id="pay_way">
        <p>支付方式：</p>
        <ul id="payment-list">
            <li><img src="v2-0515_r.jpg" alt=""> <span>微信支付</span></li>
            <li><img src="v2-0515_r.jpg" alt=""> <span>支付宝</span></li>
            <li><img src="v2-0515_r.jpg" alt=""> <span>先用后付</span></li>
            <li><img src="v2-0515_r.jpg" alt=""> <span>花呗</span></li>
            <li><img src="v2-0515_r.jpg" alt=""> <span>QQ钱包</span></li>
        </ul>
    </div>
    <div id="go_pay">
        <button id="pay">支付</button>
        <p>应付：<span></span></p>
    </div>
</section>
<%@include file="footer.jsp" %>
<script src="js/jquery.min.js"></script>
<script>

    window.onload = function () {
        const params = new URLSearchParams(window.location.search);
        const commodityId = params.get("commodityId");
        getBuyCommodityId(commodityId)
    }
    let htmlCommodity, htmlAddress = "";
    const store_commodity = $("#store_commodity");
    const address_is_default = $(".address_is_default");
    const address_all_li = $(".address_all_li");

    function getBuyCommodityId(commodityId) {
        let user = localStorage.getItem("userJson");
        let userId;
        user = eval('(' + user + ')');
        if (user != null) {
            userId = user.userId;
        } else {
            alert("请登录后，再购买！");
            return;
        }
        $.ajax({
            type: "POST",
            url: "commodity/getBuyCommodityId",
            data: {
                commodityId: commodityId,
                userId: userId
            },
            success: function (res) {
                if (res.msg == "success") {
                    address_all_li.empty();
                    address_is_default.empty();
                    htmlCommodity =
                        "<div id=\"Store\">" +
                        "<img src='../" + res.data.store.storeImg + "'>" +
                        "<p>" + res.data.store.storeName + "></p> </div> <div id=\"commodity\">" +
                        "<img src='../" + res.data.commodityImgList[0].commodityImg + "'>" +
                        "<div id=\"commodity_details\">" +
                        "<p>" + res.data.commodityName + "</p>" +
                        "<p class=\"price\">价格：<span>￥" + (res.data.commodityPrice * 0.9).toFixed(2) + "</span></p>" +
                        "<p class=\"market_price\">市场价格：<span>" + res.data.commodityPrice + "</span></p>" +
                        "<p>数量： <button id='decrementButton' onclick='decrementButton()' disabled>−</button>" +
                        "<input type=\"text\" id='counter' onclick='CountToggle()' value=\"1\">" +
                        "<button id='incrementButton' onclick='incrementButton()'>+</button> </p> </div> </div>";
                    store_commodity.append(htmlCommodity);
                    for (let i = 0; i < res.address.userAddressList.length; i++) {
                        if (res.address.userAddressList[i].isDefault == 1) {
                            htmlAddress =
                                "<li class=\"address_lie address_pick\">" +
                                "<input type=\"hidden\" name=\"\" id='addressId' value='"+res.address.userAddressList[i].addressId+"'>"+
                                "<label class=\"address_checkmark\">📌</label>" +
                                "<p><span>" + res.address.userAddressList[i].name + "</span> <span>" + res.address.userAddressList[i].phone + "</span></p>" +
                                "<p>" + res.address.userAddressList[i].address + "</p>" +
                                "</li><button id='address_all' onclick='address_all_toggle()'>修改</button>";
                            address_is_default.append(htmlAddress);
                        }
                        htmlAddress =
                            "<li class=\"address_lie\">";
                        if (res.address.userAddressList[i].isDefault == 1) {
                            htmlAddress += "<label class=\"address_checkmark\">📌</label>";
                        }
                        htmlAddress +=
                            "<input type=\"hidden\" name=\"\" class='userId' value='"+res.address.userId+"'>"+
                            "<input type=\"hidden\" name=\"\" class='addressId' value='"+res.address.userAddressList[i].addressId +"'>"+
                            "<p><span>" + res.address.userAddressList[i].name + "</span> <span>" + res.address.userAddressList[i].phone + "</span></p>" +
                            "<p>" + res.address.userAddressList[i].address + "</p>" +
                            "<button class=\"pick\" onclick='updateAddress(this)'>选择</button></li>";
                        address_all_li.append(htmlAddress);
                        $("#go_pay p span").text($(".price span").text());

                    }
                }
            },
            error: function () {
                alert("error");
            }
        });
    }
    // 添加地址
    function addAddress(){
        const userId = $(".userId").val();
        const name = $("#name").val();
        const phone = $("#phone").val();
        const address_name = $("#address_name").val();
        let is_default = $("#default").prop('checked');
        if (is_default == true){
            is_default = 1;
        }else{
            is_default = 0;
        }
        $.ajax({
            type: "POST",
            url: "address/addAddress",
            data:{
                userId:userId,
                name:name,
                phone:phone,
                address:address_name,
                isDefault:is_default
            },
            success:function (res){
                if (res == "success"){
                    alert("添加成功");
                    $("#address_add").toggle(200);
                    const params = new URLSearchParams(window.location.search);
                    const commodityId = params.get("commodityId");
                    getBuyCommodityId(commodityId);
                }else if (res == "fail"){
                    alert("添加失败")
                }
            },
            error:function(){
                alert("error")
            }
        })
    }
    // 选择地址
    function updateAddress(el) {
        const userId = $(".userId").val();
        const addressId = $(el).prev().prev().prev(".addressId").val();
        $.ajax({
            type: "POST",
            url: "address/updateAddressIsDefault",
            data:{
                userId:userId,
                addressId:addressId
            },
            success:function (res){
                if (res == "success"){
                    alert("修改成功")
                    location.reload();
                }else if (res == "fail"){
                    alert("修改失败")
                }
            },
            error:function (){
                alert("error")
            }
        })
    };
    // 购买限制
    function incrementButton () {
        var count = $("#counter").val();
        const price = $(".price span").text().replace("￥", "");

        count++;
        if (count > 100) {
            alert("最多购买100");
            count = 100;
        }
        $('#counter').val(count);
        $("#go_pay p span").text("￥"+(price * count).toFixed(2));
        if (count > 1) {
            $('#decrementButton').prop('disabled', false);
        }
    };
    function decrementButton() {
        var count = $("#counter").val();
        const price = $(".price span").text().replace("￥", "");
        if (count > 1) { // 检查是否大于1，如果是1则不减少
            count--;
            $('#counter').val(count);
            $("#go_pay p span").text("￥"+(price * count).toFixed(2));
        } else {
            $(this).prop('disabled', true); // 如果为1，则禁用减号按钮
        }
    };
        function CountToggle() {
            $("#counter").on("input", function () {
                var count = $("#counter").val();
                const price = $(".price span").text().replace("￥", "");
                console.log(price)
                if (count > 100) {
                    alert("最多购买100");
                    count = 100;
                }
                $('#counter').val(count);
                $("#go_pay p span").text("￥"+(price * count).toFixed(2));
            });
        }
        $('#payment-list li .checkmark').remove();
        $('#payment-list li').click(function (e) {
            e.preventDefault();
            $('#payment-list li .checkmark').remove();
            $(this).append('<i class="checkmark">✔</i>');
        });

    function address_all_toggle() {
        $("#address_all").toggle();
        $("#add_address").toggle();
        $("#address_table").toggle(200);
    }
    function add_address(){
        $("#address_all").toggle();
        $("#add_address").toggle();
        $("#address_add").toggle(200);
    }
    $("#pay").click(function () {
        const userId = $(".userId").val();
        const commodityId = getUrlParams("commodityId");
        const addressId = $("#addressId").val();
        const number = $("#counter").val();
        const totalAmount =$("#go_pay p span").text().replace("￥", "");
        // 获取payment-list下的所有li元素
        const listItems = $('#payment-list li');
        let payment_method = null;
        // 遍历所有的li元素
        listItems.each(function() {
            // 如果li元素中存在<i class="checkmark">✔</i>元素
            if ($(this).find('.checkmark').length > 0) {
                // 返回该li元素中的span元素的文本内容
                payment_method = $(this).find('span').text();
            }
        });
        $.ajax({
            type: "post",
            url: "order/addOrder",
            data:{
                commodityId:commodityId,
                addressId:addressId,
                number:number,
                userId:userId,
                paymentMethod:payment_method,
                totalAmount:totalAmount
            },
            success:function (res){
                if (res == "success"){
                    window.location.href = "addToOrder.jsp";
                }else if (res = "fail"){
                    alert("支付失败")
                }
            },
            error:function (){
                alert("error")
            }
        })
    })

    //初始化url参数
    function initParams() {
        if (getUrlParams('date') == null) {
            date = "0";
        } else {
            date = getUrlParams('date');
        }
        if (getUrlParams('brand') == null) {
            brand = "0";
        } else {
            brand = getUrlParams('brand');
        }
        if (getUrlParams('area') == null) {
            area = "0";
        } else {
            area = getUrlParams('area');
        }
        if (getUrlParams('hall') == null) {
            hall = "0";
        } else {
            hall = getUrlParams('hall');
        }
        if (getUrlParams('page') == null) {
            page = "1";
        } else {
            page = getUrlParams('page');
        }
    }

    //获取url参数
    function getUrlParams(name) { // 不传name返回所有值，否则返回对应值
        var url = window.location.search;
        if (url.indexOf('?') == 1) {
            return false;
        }
        url = url.substr(1);
        url = url.split('&');
        var name = name || '';
        var nameres;
        // 获取全部参数及其值
        for (var i = 0; i < url.length; i++) {
            var info = url[i].split('=');
            var obj = {};
            obj[info[0]] = decodeURI(info[1]);
            url[i] = obj;
        }
        // 如果传入一个参数名称，就匹配其值
        if (name) {
            for (var i = 0; i < url.length; i++) {
                for (const key in url[i]) {
                    if (key == name) {
                        nameres = url[i][key];
                    }
                }
            }
        } else {
            nameres = url;
        }
        // 返回结果
        return nameres;
    }
</script>
</body>
</html>
